import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { ElTree } from 'element-plus';

import { callList, addCall, updateCall, delCall, GetAllCall } from '@/utils/api/BasicManagement/calling'
import { GetAllStation } from '@/utils/api/dispatch/station'
import { GetStorePlaceList } from '@/utils/api/BasicManagement/locations'

export function useDept() {
  const form = reactive({
    name: "",
    pageNumber: 0,
    pageSize: 10,
    sortName: "createtime",
    sortType: 0
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 状态select
  const statusSelect = ref([
    { value: 1, label: '启用' },
    { value: 0, label: '禁用' },
  ])
  // 站点select
  let stationSelect = ref([])
  // 关联网关
  let affiliationSelect = ref([])

  const columns: TableColumnList = [
    // {
    //   label: "编码",
    //   prop: "code",
    //   width: 150,
    //   align: "left",
    //   sortable: true
    // },
    {
      label: "名称",
      prop: "name",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "IP地址",
      prop: "ip",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "通讯端口",
      prop: "port",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "设备号",
      prop: "number",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "状态",
      prop: "status",
      width: 110,
      sortable: true,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "备注",
      prop: "note",
      align: "left",
      sortable: true
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ]

  async function onSearch() {
    loading.value = true;
    const { Content } = await callList(form);
    let newData = Content.Results;
    dataList.value = newData;
    pagination.total = Content.TotalCount;
    pagination.pageSize = Content.PageSize;
    pagination.currentPage = Content.PageNumber + 1;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}呼叫设备`,
      props: {
        formInline: {
          code: row?.code ?? "",
          name: row?.name ?? "",
          ip: row?.ip ?? "",
          port: row?.port ?? null,
          status: row?.status ?? 1,
          number: row?.number ?? "",
          note: row?.note ?? "",
          callboxList: row?.callboxList ?? [{status:1}]
        },
        statusSelect: statusSelect.value || [],
        stationSelect: stationSelect.value || [],
        affiliationSelect: affiliationSelect.value || [],
      },
      width: "35%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      //@ts-ignore
      contentRenderer: () => h(elForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了呼叫设备名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
                //@ts-ignore
              addCall(curData).then(res => {
                if (res.Code === 0) chores();
              })
            } else {
              let data = Object.assign(curData, { id: row.id })
              //@ts-ignore
              updateCall(data).then(res => {
                if (res.Code === 0) chores();
              })
            }
          }
        });
      }
    })
  }

  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否确认删除名称为${row.name}的数据项?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      delCall(row.id).then(res => {
        if (res.Code === 0) {
          message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    form.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.pageNumber = val - 1
    onSearch()
  }

  onMounted(async () => {
    onSearch()
    // 关联工位
    let { Content: store } = await GetStorePlaceList({})
    stationSelect.value = store
  })

  return {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    statusSelect
  }
}